import java.io.*;
import java.net.Socket;

public class ChatChannel implements Runnable {
    private Socket socket;
    private ObjectInputStream ois;
    private String name;
    private ObjectOutputStream oos;

    public ChatChannel(Socket socket){
        this.socket=socket;
    }
    public void run() {
        try {
            recvNameAndEchoHello();
            //服务器端增加收发代码
            while(true){
                String msg= (String) ois.readObject();
                System.out.println(name +"说:"+msg);
                //返回给客户端
                oos.writeObject(name +"说:"+msg);
                oos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void recvNameAndEchoHello() throws IOException, ClassNotFoundException {
        //获得socket对应的输入流对象，准备接收客户端的输入
        InputStream is= socket.getInputStream();
        //将最基础的InputStream对象包装成对象流
        ois = new ObjectInputStream(is);
        //调用对象流的readObject()方法接收客户端的输入的姓名
        name = (String) ois.readObject();

        //输出客户端进入聊天室的提示信息
        System.out.println(name +"进入聊天室");

        //向客户端发送欢迎信息
        //获得与客户端通信的输出流对象
        OutputStream os=socket.getOutputStream();
        //将最基础的OutputStream对象包装成对象流
        oos = new ObjectOutputStream(os);
        //调用对象流的writeObject()方法向客户端发送欢迎信息
        oos.writeObject(name + "，您好!欢迎您进入聊天室");
        oos.flush();
    }

}
